/**
 * 版权所有(C)，上海勾芒信息科技，2017，所有权利保留。
 * 
 * 项目名：	cards-web
 * 文件名：	WxAppAuthorizerAccessTokenStorage.java
 * 模块说明：	
 * 修改历史：
 * 2017年5月25日 - Debenson - 创建。
 */
package com.alex.wechat.component.config.impl;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.util.ApplicationContextUtil;

import com.alex.wechat.app.account.entity.WxAppAccountEntity;
import com.alex.wechat.app.account.service.WxAppAccountServiceI;
import com.alex.wechat.component.config.AuthorizerAccessTokenStorage;
import com.alex.wechat.component.config.WxComponentContext;
import com.gomore.jeecg.common.Assert;

/**
 * 小程序的第三方授权凭证存储实现。
 * 
 * @author Debenson
 * @since 0.1
 */
public class WxAppAuthorizerAccessTokenStorage implements AuthorizerAccessTokenStorage {

  private final WxAppAccountEntity account;

  public WxAppAuthorizerAccessTokenStorage(WxAppAccountEntity account) {
    Assert.assertArgumentNotNull(account, "account");
    this.account = account;
  }

  @Override
  public String getAuthorizerAccessToken() {
    return account.getAuthorizerAccessToken();
  }

  @Override
  public boolean isAuthorizerAccessTokenExpired() {
    long expiresTime = (account.getAuthorizerAccessTokenExpiresIn() == null
        || StringUtils.isBlank(account.getAuthorizerAccessToken())) ? 0L
            : account.getAuthorizerAccessTokenExpiresIn();
    return System.currentTimeMillis() > expiresTime;
  }

  @Override
  public void expireAuthorizerAccessToken() {
    account.setAuthorizerAccessTokenExpiresIn(0L);
    try {
      WxAppAccountServiceI service = ApplicationContextUtil.getBean(WxAppAccountServiceI.class);
      service.saveOrUpdate(account);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public void updateAuthorizerAccessToken(String token, int expiresInSeconds) {
    updateAuthorizerAccessToken(token, expiresInSeconds, account.getAuthorizerRefreshToken());
  }

  @Override
  public void updateAuthorizerAccessToken(String token, int expiresInSeconds,
      String authorizerRefreshToken) {
    account.setAuthorizerAccessToken(token);
    account.setAuthorizerRefreshToken(authorizerRefreshToken);
    // 保存所属第三方开发平台id
    account.setComponentAppId(WxComponentContext.getAppId());
    long expiresIn = 0L;
    if (StringUtils.isNotBlank(token)) {
      expiresIn = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L;
    }
    account.setAuthorizerAccessTokenExpiresIn(expiresIn);

    try {
      WxAppAccountServiceI service = ApplicationContextUtil.getBean(WxAppAccountServiceI.class);
      service.saveOrUpdate(account);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public String getAuthorizerRefreshToken() {
    return account.getAuthorizerRefreshToken();
  }
}
